package b.h.y.bj.base;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.viewpagerindicator.CirclePageIndicator;

import org.w3c.dom.Text;

import java.util.List;

import b.h.y.bj.NewsDetailActivity;
import b.h.y.bj.R;
import b.h.y.bj.domain.NewsData;
import b.h.y.bj.domain.TabData;
import b.h.y.bj.global.GlobalContants;
import b.h.y.bj.util.CacheUtils;
import b.h.y.bj.util.SharedPreferencesUtil;
import b.h.y.bj.view.RefreshListView;

/**
 * 页签详情页
 * Created by YHB on 2016/1/5.
 */
public class TabDetailPager extends BaseMenuDetailPager implements ViewPager.OnPageChangeListener {


    private NewsData.NewsTabData newsTabDatas;
    private TabData tabData; //tabData数据
    private List<TabData.TopNewsData> topNewsDatas; //头条新闻

    private List<TabData.TabNewsData> newsDatas; //新闻列表数据

    @ViewInject(R.id.vp_news)
    private ViewPager viewPager;


    @ViewInject(R.id.lv_list)
    private RefreshListView listView;

    @ViewInject(R.id.tv_news_title)
    private TextView mTvNewsTitle; //标题

    @ViewInject(R.id.cp_indicator)
    private CirclePageIndicator circlePageIndicator;

    private TopNewsAdapter topNewsAdapter;
    private String mMoreUrl;
    private NewsAdapter newsAdapter;


    private Handler mHandler;

    public TabDetailPager(Activity activity, NewsData.NewsTabData mNewsTabData) {
        super(activity);
        newsTabDatas = mNewsTabData;
    }

    public TabDetailPager(Activity activity) {
        super(activity);
    }

    @Override
    public View initViews() {
        View view = View.inflate(mActivity, R.layout.tab_detail_pager, null);
        View headerView = View.inflate(mActivity, R.layout.list_header_topnews, null);

        ViewUtils.inject(this, view);
        ViewUtils.inject(this, headerView);

        //将头条新闻作为listview的HeaderView
        listView.addHeaderView(headerView);

        listView.setOnRefreshListener(new RefreshListView.OnRefreshListener() {
            @Override
            public void onRrefresh() {
                fetchDataFromServer();
            }

            //加载更多
            @Override
            public void onLoadMore() {
                if (mMoreUrl != null) {
                    fetchMoreDataFromServer();
                } else {
                    Toast.makeText(mActivity, "最后一页了", Toast.LENGTH_SHORT).show();
                    listView.OnRefreshComplete(true); //隐藏脚标
                }
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                System.out.println("点击position: " + position);
                String ids = SharedPreferencesUtil.getString(mActivity, "read_ids", "");
                String _id = newsDatas.get(position).id + ",";
                if (!ids.contains(_id)) {
                    ids += _id;
                    SharedPreferencesUtil.setString(mActivity, "read_ids", ids);
                }
                changeReadState(view);

                //跳转到新闻详情页
                Intent intent = new Intent();
                intent.setClass(mActivity, NewsDetailActivity.class);
                intent.putExtra("url", newsDatas.get(position).url);
                mActivity.startActivity(intent);

                //newsAdapter.notifyDataSetChanged();
            }
        });

        return view;
    }

    /**
     * 改变已读的新闻颜色
     */
    private void changeReadState(View view) {
        TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
        tvTitle.setTextColor(Color.GRAY);
    }

    @Override
    public void initData() {
        String cache = CacheUtils.getCache(mActivity, GlobalContants.HOST + newsTabDatas.url);
        if (!TextUtils.isEmpty(cache)) {
            parseData(cache, false);
        }
        fetchDataFromServer();
    }

    /**
     * 获取数据
     */
    private void fetchDataFromServer() {
        System.out.println("获取服务器数据");
        HttpUtils utils = new HttpUtils();
        utils.send(HttpRequest.HttpMethod.GET, GlobalContants.HOST + newsTabDatas.url, new RequestCallBack<Object>() {

            @Override
            public void onSuccess(ResponseInfo<Object> responseInfo) {
                listView.OnRefreshComplete(true); //收起下拉刷新的控件
                String result = (String) responseInfo.result;
                CacheUtils.setCache(mActivity, GlobalContants.HOST + newsTabDatas.url, result);
                parseData(result, false);
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                listView.OnRefreshComplete(false); //收起下拉刷新的控件
                Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
                error.printStackTrace();
            }
        });
    }

    /**
     * 获取更多数据
     */
    private void fetchMoreDataFromServer() {
        System.out.println("获取服务器数据");
        HttpUtils utils = new HttpUtils();
        utils.send(HttpRequest.HttpMethod.GET, mMoreUrl, new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> responseInfo) {
                listView.OnRefreshComplete(true); //收起下拉刷新的控件
                String result = (String) responseInfo.result;
                parseData(result, true);
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                listView.OnRefreshComplete(false); //收起下拉刷新的控件
                Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
                error.printStackTrace();
            }
        });
    }

    /**
     * 格式化数据
     *
     * @param result
     */
    private void parseData(String result, boolean isLoadMore) {
        Gson gson = new Gson();
        tabData = gson.fromJson(result, TabData.class);

        String more = tabData.data.more;
        if (!TextUtils.isEmpty(more)) {
            mMoreUrl = GlobalContants.HOST + more;
        } else {
            mMoreUrl = null;
        }

        if (isLoadMore) { //正在加载下一页
            newsDatas.addAll(tabData.data.news);
            newsAdapter.notifyDataSetChanged();
        } else { // 加载第一页
            topNewsDatas = tabData.data.topnews; //头条新闻列表数据
            newsDatas = tabData.data.news; //新闻列表

            if (topNewsDatas != null) {
                topNewsAdapter = new TopNewsAdapter();
                viewPager.setAdapter(topNewsAdapter);

                circlePageIndicator.setViewPager(viewPager);
                //circlePageIndicator.setSnap(true); //表示快照显示

                circlePageIndicator.setOnPageChangeListener(this);

                circlePageIndicator.onPageSelected(0); //让指示器回到第一个

                //设置初始的text
                mTvNewsTitle.setText(topNewsDatas.get(0).title);
            }

            if (newsDatas != null) {
                newsAdapter = new NewsAdapter();
                listView.setAdapter(newsAdapter);
            }

            if (mHandler == null) {
                mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        int current = viewPager.getCurrentItem();
                        if (current < topNewsDatas.size() - 1) {
                            current++;
                        } else {
                            current = 0;
                        }
                        viewPager.setCurrentItem(current);
                        mHandler.sendEmptyMessageDelayed(0, 3000);
                    }
                };
                mHandler.sendEmptyMessageDelayed(0, 3000);
            }
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        mTvNewsTitle.setText(topNewsDatas.get(position).title);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 头条新闻viewpager适配器
     */
    class TopNewsAdapter extends PagerAdapter {

        private final BitmapUtils utils;

        public TopNewsAdapter() {
            utils = new BitmapUtils(mActivity);
            utils.configDefaultLoadingImage(R.drawable.topnews_item_default);
        }

        @Override
        public int getCount() {
            return topNewsDatas.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(mActivity);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY); //ScaleType.FIT_XY: 基于大小去填充图片

            utils.display(imageView, topNewsDatas.get(position).topimage);
            container.addView(imageView);

            //如果用户按住头条新闻的图片,则viewpager不自动滑动
            imageView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    switch (motionEvent.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            System.out.println("按下");
                            mHandler.removeCallbacksAndMessages(null); //删除handler的所有消息
                            break;
                        case MotionEvent.ACTION_CANCEL:
                            System.out.println("取消");
                            mHandler.sendEmptyMessageDelayed(0, 3000);
                            break;
                        case MotionEvent.ACTION_UP:
                            System.out.println("抬起");
                            mHandler.sendEmptyMessageDelayed(0, 3000);
                            break;
                    }
                    return true;
                }
            });
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    /**
     * 新闻列表的适配器
     */
    class NewsAdapter extends BaseAdapter {

        BitmapUtils bitmapUtils;

        public NewsAdapter() {
            bitmapUtils = new BitmapUtils(mActivity);
            bitmapUtils.configDefaultLoadingImage(R.drawable.pic_item_list_default);
        }

        @Override
        public int getCount() {
            return newsDatas.size();
        }

        @Override
        public Object getItem(int i) {
            return newsDatas.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder;
            if (view == null) {
                viewHolder = new ViewHolder();
                view = View.inflate(mActivity, R.layout.list_news_item, null);
                viewHolder.ivImage = (ImageView) view.findViewById(R.id.iv_news_img);
                viewHolder.tvTitle = (TextView) view.findViewById(R.id.tv_title);
                viewHolder.tvDate = (TextView) view.findViewById(R.id.tv_date);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }

            TabData.TabNewsData item = (TabData.TabNewsData) getItem(i);
            viewHolder.tvDate.setText(item.pubdate);
            viewHolder.tvTitle.setText(item.title);
            bitmapUtils.display(viewHolder.ivImage, item.listimage);

            String ids = SharedPreferencesUtil.getString(mActivity, "read_ids", "");
            if (ids.contains(item.id + ",")) {
                viewHolder.tvTitle.setTextColor(Color.GRAY);
            } else {
                viewHolder.tvTitle.setTextColor(Color.BLACK);
            }
            return view;
        }
    }

    class ViewHolder {
        public TextView tvTitle;
        public TextView tvDate;
        public ImageView ivImage;
    }
}